<template>
  <div class="page-box">
    <div class="qr-container">
      <div class="qr-box">
        <div id="reader"></div>
      </div>
    </div>
    <div class="btn-box">
      <div>
        <van-icon name="arrow-left" @click="clickBack" />
      </div>
      <div>
        <van-uploader
          v-model="state.fileList"
          :preview-image="false"
          :after-read="uploadImg"
        >
          <van-icon name="photo-o"
        /></van-uploader>
      </div>
    </div>
  </div>
</template>
<script setup>
import { reactive, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { Html5Qrcode } from "html5-qrcode";
import qrcodeParser from "qrcode-parser";
import { showToast } from "vant";
const router = useRouter();
const state = reactive({
  html5QrCode: null,
  fileList: [],
});

function clickBack() {
  router.push({ path: "/home" });
}

function url2Obj(url) {
  //获取字符串 ? 后面的部分
  const queryString = url.split("?")[1];
  const paramsArr = queryString.split("&");
  const paramObj = {};

  paramsArr.forEach((param) => {
    const [key, value] = param.split("=");
    paramObj[key] = decodeURIComponent(value);
  });

  return paramObj;
}

function getCamerasInfo() {
  Html5Qrcode.getCameras()
    .then((devices) => {
      if (devices && devices.length) {
        state.html5QrCode = new Html5Qrcode("reader");
        startScan();
      }
    })
    .catch((err) => {
      state.html5QrCode = new Html5Qrcode("reader");
    });
}

function startScan() {
  state.html5QrCode
    .start(
      { facingMode: "environment" },
      {
        fps: 10,
        qrbox: { width: 250, height: 250 },
      },
      (decodedText) => {
        const query = url2Obj(decodedText);
        router.push({
          path: "/scanResult",
          query: {
            code: query.code || "",
          },
        });
      }
    )
    .catch((err) => {
      console.log("扫码失败", err);
    });
}

function stopScan() {
  state.html5QrCode
    .stop()
    .then((a) => {
      console.log("已停止扫码", a);
    })
    .catch((err) => {
      console.log(err);
      showToast("停止失败");
    });
}

function uploadImg() {
  try {
    state.html5QrCode.qrcode.callback = (result) => {
      showToast(result);
    };
    let file = state.fileList[0].file;
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      //解析二维码图片
      qrcodeParser(file)
        .then((res) => {
          const query = url2Obj(res);
          router.push({
            path: "/scanResult",
            query: {
              code: query.code || "",
            },
          });
        })
        .catch((err) => {
          console.log("error", err);
        });
    };
  } catch (error) {
    console.log(error);
    showToast({
      message: "识别失败！",
      duration: 2000,
    });
  }
}

onMounted(() => {
  setTimeout(() => {
    getCamerasInfo();
  }, 500);
});
onUnmounted(() => {
  if (state.html5QrCode?.isScanning) {
    stopScan();
  }
});
</script>
<style scoped>
.page-box {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  background: #000;
  overflow: hidden;
}
.qr-container {
  position: relative;
  width: 100%;
  flex: 1;
}
.qr-box {
  position: relative;
  height: 100%;
}
#reader {
  top: 10%;
  left: 0;
}
.btn-box {
  height: 60px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: auto;
  padding: 12px 12px 20px;
  color: #fff;
  flex-shrink: 0;
  font-size: 28px;
}
</style>
